<template>
  <div class="attr-item">
    <div class="attr-item-ul" ref="sortList">
      <div
        class="attr-item-ul-li"
        v-for="(item, index) in curStatisticList"
        :key="item.id"
      >
        <a class="li-title" @click="methods.onChangeEditItem(item, index)">
          <Icon icon="ant-design:holder-outlined" />
          {{ item.title }}
        </a>
        <div class="li-icon" @click="methods.onChangeEditItem(item, index)">
          <Icon icon="ant-design:form-outlined" />
        </div>
        <div class="li-icon" @click="methods.onDeleteItem(index)">
          <Icon icon="ant-design:delete-outlined" />
        </div>
      </div>
      <a-button class="attr-item-add" @click="methods.onAddItem">
        添加一项
      </a-button>
    </div>

    <a-modal v-model:open="isEdit" title="修改标签项" @ok="methods.onConfirm">
      <div class="item-edit">
        <BwConfigInput v-model:value="curEditItem.title" title="标题" />
        <BwConfigInput v-model:value="curEditItem.explain" title="统计栏释义" />
        <BwConfigSwitch
          v-model:value="curEditItem.isDefault"
          title="是否默认"
        />
        <BwConfigSwitch v-model:value="curEditItem.isEnable" title="是否启用" />
        <BwConfigSwitch
          v-model:value="curEditItem.isStatistic"
          title="是否纳入统计"
        />
        <BwConfigCondition
          v-model:condition="curEditItem.condition"
          :options="dataKeyOptions"
          title="条件"
        />
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts">
import {
  PropType,
  computed,
  defineComponent,
  nextTick,
  onMounted,
  ref,
  watch,
} from 'vue'

import { BwFilterTableStatisticListModel } from './model'

import { cloneDeep } from 'lodash-es'

import Sortable from 'sortablejs'
import { bwUtils } from '@/utils/main'
import { BwFilterTableTreeListFieldsModel } from '../comItems/model'
import BwConfigInput from '../comItems/input/index.vue'
import BwConfigSwitch from '../comItems/switch/index.vue'
import BwConfigCondition from '../comItems/condition/index.vue'
import { api, useAxiosResponse } from '/@/api'
import { BwPageResultOutputSysDataObjectAppGetFieldOutput } from '@bitwit/tenantapi'

export default defineComponent({
  name: 'BwFilterTableStatisticList',
  components: {
    BwConfigInput,
    BwConfigCondition,
    BwConfigSwitch,
  },
  props: {
    value: {
      type: [Array] as PropType<BwFilterTableStatisticListModel[]>,
      default: () => [],
    },
    dataObjId: {
      type: [String, Number],
    },
  },
  emits: ['update:value', 'change'],
  setup(props, { emit }) {
    /** 对象值 */
    const curStatisticList = computed({
      get: (): BwFilterTableStatisticListModel[] => {
        return props.value ?? []
      },
      set: (value) => {
        emit('update:value', value)
        emit('change', value)
      },
    })

    const sortList = ref()

    /** 当前编辑项 */
    const curEditItem = ref({} as BwFilterTableStatisticListModel)
    /** 当前编辑项下标 */
    const curEditIndex = ref(0)

    /** 是否编辑 */
    const isEdit = ref(false)

    const methods = {
      onChangeEditItem(item: BwFilterTableStatisticListModel, index: number) {
        curEditItem.value = cloneDeep(item)
        curEditIndex.value = index
        isEdit.value = true
      },
      onDeleteItem(index: number) {
        curStatisticList.value =
          curStatisticList.value.filter((_, i) => i !== index) ?? []
      },
      onAddItem() {
        curEditIndex.value = curStatisticList.value?.length
        curEditItem.value = {
          id: bwUtils.getGuid(),
          isEnable: true,
          isStatistic: true,
        }
        isEdit.value = true
      },
      onConfirm() {
        isEdit.value = false
        let arr = cloneDeep(curStatisticList.value)
        arr[curEditIndex.value] = curEditItem.value
        curStatisticList.value = arr
      },
      /** 初始化拖拽 */
      initSortableItem() {
        if (sortList.value.value) {
          new Sortable(sortList.value, {
            animation: 150,
            onEnd: (evt) => {
              const { newIndex, oldIndex } = evt
              if (newIndex === oldIndex) return
              const arr = [...curStatisticList.value]
              const item = arr.splice(oldIndex ?? 0, 1)[0]
              arr.splice(newIndex ?? 0, 0, item)
              nextTick(() => {
                curStatisticList.value = [...arr]
              })
              return false
            },
          })
        }
      },
      /** 获取数据字段类型 */
      getDataKeyOptions(dataObjectId?: string | number) {
        return new Promise((resolve, reject) => {
          api
            .apiSysDataObjectGetFieldsPost({
              dataObjectId: dataObjectId?.toString(),
            })
            .then((res) => {
              const resData =
                useAxiosResponse<BwPageResultOutputSysDataObjectAppGetFieldOutput>(
                  res
                )
              dataKeyOptions.value =
                resData?.rows
                  ?.filter((item) => item.id)
                  ?.map((item) => {
                    return {
                      label: item.code ?? '未命名字段',
                      value: item.id ?? '',
                    }
                  }) ?? []
              resolve(resData)
            })
            .catch((err) => {
              reject(err)
            })
        })
      },
    }

    /** 数据字段列表 */
    const dataKeyOptions = ref<BwFilterTableTreeListFieldsModel[]>([])
    watch(
      () => props.dataObjId,
      (newVal) => {
        methods.getDataKeyOptions(newVal)
      },
      { immediate: true }
    )

    onMounted(() => {
      methods.initSortableItem()
    })

    return {
      curStatisticList,
      sortList,
      isEdit,
      curEditItem,
      methods,
      dataKeyOptions,
    }
  },
})
</script>

<style lang="less" scoped>
.attr-item {
  max-height: 70%;
  overflow: auto;

  .attr-item-ul {
    padding: 8px;
    background: #edeff3;
    margin: 8px;

    .attr-item-ul-li {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      line-height: 28px;
      height: 28px;
      white-space: nowrap;

      .li-title {
        flex: 1;
        font-size: 12px;
      }

      .li-icon {
        font-size: 16px;
        cursor: pointer;
        margin-left: 8px;
        opacity: 0.6;

        &:hover {
          opacity: 1;
        }
      }
    }
  }

  .attr-item-add {
    width: 100%;
  }
}

.item-edit {
  padding: 24px;
}
</style>
